package question;

import java.util.Random;

/**
 * 问题4：抢红包
 *
 * @author 阳秋豪
 * @问题描述 假设:100块，分成了3个包，现在有5个人去抢，m其中，红包是共享数据。
 * 5个人是5条线程。
 * 打印结果如下
 * XXX抢到了XXX元
 * XXX抢到了XXX元
 * XXX抢到了XXX元
 * XXX没抢到
 * XXX没抢到
 * @createTime 2024/3/12
 */
public class Test4 {
    public static void main(String[] args) {
        QOneRunnable4 runnable = new QOneRunnable4();
        Thread t1 = new Thread(runnable);
        Thread t2 = new Thread(runnable);
        Thread t3 = new Thread(runnable);
        Thread t4 = new Thread(runnable);
        Thread t5 = new Thread(runnable);
        t1.setName("A");
        t2.setName("B");
        t3.setName("C");
        t4.setName("D");
        t5.setName("E");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
        t5.start();
    }
}

class QOneRunnable4 implements Runnable {
    // 红包总金额
    double redPacket = 100.0;
    // 红包数量
    int count = 3;
    Random random = new Random();
    // 最小中奖金额
    final double MIN = 0.01;
    // 抢到的金额
    double money = 0;
    @Override
    public void run() {
        synchronized (QOneRunnable4.class) {
            if (count == 0) {
                System.out.println(Thread.currentThread().getName() + "没抢到");
            } else {
                if (count == 1) {
                    money = redPacket;
                } else {
                    money = random.nextDouble() * (redPacket - (count - 1) * MIN);
                    if (money < MIN) {
                        money = MIN;
                    }
                }
                redPacket -= money;
                count--;
                System.out.println(Thread.currentThread().getName() + "抢到了" + money + "元");
            }
        }
    }
}